﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using Silvermoon.Controls;
using Silvermoon.UI;
using Silvermoon.Images;
using Silvermoon.Windows;
using ShoppingList.Biz;
using ShoppingList.DTO;
using Silvermoon.Controls.Forms;
using Silvermoon.Controls.Buttons;
using Silvermoon.Navigation;
using ShoppingList.Utils;
using Silvermoon.OpenGL;
using System.Drawing;

namespace ShoppingList.Pages
{
    public class NewOrEditArticlePage : Page
    {

        private TextBox textBox;
        private ToolbarButton okButton;
        private Article article;
        private Button categoryBtn;
        private bool doFocus = true;

        public NewOrEditArticlePage(Article article)
            : base()
        {
            if (article == null) throw new ArgumentNullException("article");

            this.Article = article;
            InitializePage();
        }

        public Article Article
        {
            get { return article; }
            private set { article = value; }
        }

        public string CategoryName
        {
            get { return (article != null && article.Category != null) ? article.Category.Name : "no category"; }
        }

        private void InitializePage()
        {
            KeepAlive = true;
            Styles = StylePool.Main;
            Title = "NEW ARTICLE";
            SetTransition(300, TransitionMask.Fade | TransitionMask.Top, TransitionMask.Fade | TransitionMask.Explode);
            Color = PhoneColors.AlphaColor(PhoneColors.Dark, 240);

            ScrollStackPanel sp = new ScrollStackPanel { Margin = new Margin(10, 10, 10, 0) };
            Controls.Add(sp);

            Label l = new Label { Text = "Article", AutoSize = true, Font = FontPool.MediumRegularFont, FontScale = 1.5f };
            sp.Controls.Add(l);

            textBox = new TextBox { Margin = new Margin(0, 10, 0, null), AutoHeight = true, Font = FontPool.MediumRegularFont, Text = Article.Name };
            textBox.TextChanged += new EventHandler(OnTextChanged);
            sp.Controls.Add(textBox);

            categoryBtn = new Button
            {
                Margin = new Margin(0, 25, 0, null),
                Height = 64,
                Content = CategoryName,
                Font = FontPool.MediumRegularFont,
                Style = ButtonStyles.PickerStyle
            };
            categoryBtn.Tap += new EventHandler<TapEventArgs>(OnChooseCategory);
            sp.Controls.Add(categoryBtn);

            Label l2 = new Label
            {
                CharSpace = 2,
                Opacity = 140,
                Margin = new Margin(0, 15, 0, null),
                AutoSize = true,
                LineMode = LineMode.WordWrap,
                Text = "Choose a category to save the article for later selection. Otherwise the article is available for this shopping list only."
            };
            sp.Controls.Add(l2);

            Toolbar tb = new Toolbar();
            okButton = tb.AddButton(SysImages.Ok);
            okButton.Enabled = false;
            okButton.Tap += new EventHandler<TapEventArgs>(OnOk);
            tb.AddButton(SysImages.RecycleBin).Tap += new EventHandler<TapEventArgs>(OnDelete);
            tb.AddButton(SysImages.Cancel).Tap += new EventHandler<TapEventArgs>(OnNewArticle);

            tb.Buttons[1].Enabled = Article.Id != 0;
            Toolbar = tb;
        }

        void OnChooseCategory(object sender, TapEventArgs e)
        {
            CategoryPicker page = new CategoryPicker();
            page.CategoryChosen += (s, ee) =>
                {
                    Category c = page.Category;
                    categoryBtn.Content = c.Name;
                    Article.Category = c;
                };
            this.NavigateTo(page, PageTransitions.InOut);
        }

        void OnDelete(object sender, TapEventArgs e)
        {
            MessageDialog.Show("Delete article?", textBox.Text + " will be deleted from your list of articles.", "Delete", "Cancel", DeleteArticle, null);
        }

        private void DeleteArticle()
        {
            if (Delete != null) Delete(this, EventArgs.Empty);
            GoBack();
        }

        void OnOk(object sender, TapEventArgs e)
        {
            Article article = Article;
            if (article != null)
            {
                article.Name = textBox.Text;
                if (article.Category == null || BizContext.Context.SaveArticle(article))
                {
                    if (Ok != null) Ok(this, EventArgs.Empty);
                    GoBack();
                }
            }
        }

        void OnTextChanged(object sender, EventArgs e)
        {
            string text = textBox.Text;
            okButton.Enabled = !string.IsNullOrEmpty(text) && !ArticleExists(text);
        }

        private bool ArticleExists(string text)
        {
            var context = BizContext.Context;
            return context.Articles.Any(s => string.Compare(text, s.Name, true) == 0);

        }

        void OnNewArticle(object sender, TapEventArgs e)
        {
            GoBack();
        }

        protected override void OnShown()
        {
            base.OnShown();
            if (doFocus)
            {
                doFocus = false;
                textBox.SelectAll();
                textBox.SetFocus();
            }
        }

        public event EventHandler Ok;
        public event EventHandler Delete;
    }
}
